#!/usr/bin/env python3
"""
Android客户端服务器配置更新脚本
用于更新WebSocket服务器地址
"""

import os
import re
import json
from datetime import datetime

class ClientConfigUpdater:
    def __init__(self):
        self.config_file = "app/src/main/java/com/example/myapplication/utils/ServerConfig.kt"
        self.backup_file = f"ServerConfig_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.kt"
        
    def backup_current_config(self):
        """备份当前配置"""
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            with open(self.backup_file, 'w', encoding='utf-8') as f:
                f.write(content)
            
            print(f"当前配置已备份到: {self.backup_file}")
            
    def update_server_url(self, server_ip, server_port=8080):
        """更新服务器URL"""
        if not os.path.exists(self.config_file):
            print(f"错误：配置文件不存在: {self.config_file}")
            return False
            
        # 读取当前配置
        with open(self.config_file, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 更新默认服务器地址
        old_pattern = r'return "ws://172\.20\.0\.94:8080"'
        new_pattern = f'return "ws://{server_ip}:{server_port}"'
        
        if re.search(old_pattern, content):
            content = re.sub(old_pattern, new_pattern, content)
            print(f"已更新默认服务器地址为: ws://{server_ip}:{server_port}")
        else:
            print("未找到默认服务器地址，可能需要手动更新")
            
        # 写入更新后的配置
        with open(self.config_file, 'w', encoding='utf-8') as f:
            f.write(content)
            
        return True
        
    def create_server_settings_activity(self):
        """创建服务器设置界面"""
        settings_activity = '''package com.example.myapplication

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.utils.ServerConfig

class ServerSettingsActivity : AppCompatActivity() {
    
    private lateinit var etServerUrl: EditText
    private lateinit var switchPublicServer: Switch
    private lateinit var btnSave: Button
    private lateinit var btnTest: Button
    private lateinit var btnReset: Button
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_server_settings)
        
        initViews()
        loadCurrentSettings()
        setupListeners()
    }
    
    private fun initViews() {
        etServerUrl = findViewById(R.id.et_server_url)
        switchPublicServer = findViewById(R.id.switch_public_server)
        btnSave = findViewById(R.id.btn_save)
        btnTest = findViewById(R.id.btn_test)
        btnReset = findViewById(R.id.btn_reset)
    }
    
    private fun loadCurrentSettings() {
        val prefs = getSharedPreferences("server_config", MODE_PRIVATE)
        val usePublicServer = prefs.getBoolean("use_public_server", false)
        val serverUrl = prefs.getString("server_url", "") ?: ""
        
        switchPublicServer.isChecked = usePublicServer
        etServerUrl.setText(serverUrl)
    }
    
    private fun setupListeners() {
        btnSave.setOnClickListener {
            saveSettings()
        }
        
        btnTest.setOnClickListener {
            testConnection()
        }
        
        btnReset.setOnClickListener {
            resetToDefault()
        }
        
        switchPublicServer.setOnCheckedChangeListener { _, isChecked ->
            etServerUrl.isEnabled = isChecked
        }
    }
    
    private fun saveSettings() {
        val serverUrl = etServerUrl.text.toString().trim()
        val usePublicServer = switchPublicServer.isChecked
        
        if (usePublicServer && serverUrl.isEmpty()) {
            Toast.makeText(this, "请输入服务器地址", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (usePublicServer) {
            ServerConfig.setPublicServerUrl(this, serverUrl)
        } else {
            ServerConfig.switchToLocalServer(this)
        }
        
        Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show()
        finish()
    }
    
    private fun testConnection() {
        val serverUrl = if (switchPublicServer.isChecked) {
            etServerUrl.text.toString().trim()
        } else {
            ServerConfig.getServerUrl(this)
        }
        
        // 这里可以添加连接测试逻辑
        Toast.makeText(this, "测试连接: $serverUrl", Toast.LENGTH_SHORT).show()
    }
    
    private fun resetToDefault() {
        switchPublicServer.isChecked = false
        etServerUrl.setText("")
        etServerUrl.isEnabled = false
        ServerConfig.switchToLocalServer(this)
        Toast.makeText(this, "已重置为默认设置", Toast.LENGTH_SHORT).show()
    }
}
'''
        
        with open("app/src/main/java/com/example/myapplication/ServerSettingsActivity.kt", 'w', encoding='utf-8') as f:
            f.write(settings_activity)
            
        print("已创建服务器设置界面: ServerSettingsActivity.kt")
        
    def create_settings_layout(self):
        """创建设置界面布局"""
        layout_content = '''<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="服务器设置"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginBottom="16dp" />

    <Switch
        android:id="@+id/switch_public_server"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="使用公网服务器"
        android:layout_marginBottom="16dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="服务器地址"
        android:textSize="16sp"
        android:layout_marginBottom="8dp" />

    <EditText
        android:id="@+id/et_server_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ws://your-server-ip:8080"
        android:inputType="textUri"
        android:enabled="false"
        android:layout_marginBottom="16dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="当前配置信息"
        android:textSize="16sp"
        android:layout_marginBottom="8dp" />

    <TextView
        android:id="@+id/tv_current_config"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F5F5F5"
        android:padding="12dp"
        android:layout_marginBottom="16dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="16dp">

        <Button
            android:id="@+id/btn_test"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="测试连接"
            android:layout_marginEnd="8dp" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="重置默认"
            android:layout_marginStart="8dp" />

    </LinearLayout>

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存设置"
        android:textSize="16sp" />

</LinearLayout>
'''
        
        with open("app/src/main/res/layout/activity_server_settings.xml", 'w', encoding='utf-8') as f:
            f.write(layout_content)
            
        print("已创建设置界面布局: activity_server_settings.xml")
        
    def update_android_manifest(self):
        """更新AndroidManifest.xml"""
        manifest_file = "app/src/main/AndroidManifest.xml"
        
        if not os.path.exists(manifest_file):
            print(f"错误：AndroidManifest.xml不存在: {manifest_file}")
            return False
            
        with open(manifest_file, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 检查是否已经添加了ServerSettingsActivity
        if 'ServerSettingsActivity' not in content:
            # 在</application>标签前添加activity声明
            content = content.replace(
                '</application>',
                '''    <activity
        android:name=".ServerSettingsActivity"
        android:exported="false"
        android:label="服务器设置" />
</application>'''
            )
            
            with open(manifest_file, 'w', encoding='utf-8') as f:
                f.write(content)
                
            print("已更新AndroidManifest.xml")
            
        return True
        
    def create_update_script(self, server_ip, server_port=8080):
        """创建更新脚本"""
        update_script = f'''@echo off
title 更新Android客户端服务器配置

echo 正在更新Android客户端配置...

REM 备份当前配置
python update_client_config.py --backup

REM 更新服务器地址
python update_client_config.py --update {server_ip}:{server_port}

REM 创建服务器设置界面
python update_client_config.py --create-ui

echo.
echo 配置更新完成！
echo.
echo 下一步操作：
echo 1. 重新编译APK
echo 2. 安装到设备测试
echo 3. 在应用中使用"服务器设置"功能切换服务器
echo.
pause
'''
        
        with open(f"update_to_{server_ip}.bat", 'w', encoding='utf-8') as f:
            f.write(update_script)
            
        print(f"已创建更新脚本: update_to_{server_ip}.bat")
        
    def show_usage_guide(self):
        """显示使用指南"""
        guide = '''
=== Android客户端配置更新指南 ===

1. 自动更新（推荐）
   运行: python update_client_config.py --update your-server-ip:8080

2. 手动更新
   - 修改 ServerConfig.kt 中的默认服务器地址
   - 重新编译APK

3. 在应用中切换服务器
   - 打开应用
   - 进入"服务器设置"
   - 选择使用本地服务器或公网服务器
   - 输入服务器地址并保存

4. 测试连接
   - 在服务器设置中点击"测试连接"
   - 检查连接状态

注意事项：
- 确保服务器地址格式正确：ws://ip:port
- 本地服务器需要确保电脑和手机在同一网络
- 公网服务器需要确保服务器正常运行
'''
        
        with open('CLIENT_CONFIG_GUIDE.md', 'w', encoding='utf-8') as f:
            f.write(guide)
            
        print(guide)

def main():
    import sys
    
    updater = ClientConfigUpdater()
    
    if len(sys.argv) < 2:
        print("用法:")
        print("  python update_client_config.py --backup")
        print("  python update_client_config.py --update server-ip:port")
        print("  python update_client_config.py --create-ui")
        print("  python update_client_config.py --guide")
        return
        
    command = sys.argv[1]
    
    if command == "--backup":
        updater.backup_current_config()
    elif command == "--update":
        if len(sys.argv) < 3:
            print("请提供服务器地址，格式：ip:port")
            return
        server_info = sys.argv[2].split(":")
        server_ip = server_info[0]
        server_port = server_info[1] if len(server_info) > 1 else "8080"
        updater.update_server_url(server_ip, server_port)
        updater.create_update_script(server_ip, server_port)
    elif command == "--create-ui":
        updater.create_server_settings_activity()
        updater.create_settings_layout()
        updater.update_android_manifest()
    elif command == "--guide":
        updater.show_usage_guide()
    else:
        print("未知命令:", command)

if __name__ == "__main__":
    main() 